package club.xyes.zkh.ecommerce.service.impl;

import club.xyes.zkh.ecommerce.commons.entity.Shop;
import club.xyes.zkh.ecommerce.commons.entity.User;
import club.xyes.zkh.ecommerce.commons.entity.UserCollectShop;
import club.xyes.zkh.ecommerce.commons.exception.BadRequestException;
import club.xyes.zkh.ecommerce.commons.exception.InternalServerErrorException;
import club.xyes.zkh.ecommerce.dao.mapper.UserCollectShopMapper;
import club.xyes.zkh.ecommerce.service.UserCollectShopService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create by 郭文梁 2019/4/18 0018 14:08
 * UserCollectShopServiceImpl
 * 用户收藏商铺相关业务行为实现
 *
 * @author 郭文梁
 * @data 2019/4/18 0018
 */
@Service
public class UserCollectShopServiceImpl extends BaseServiceImpl<UserCollectShop> implements UserCollectShopService {
    private final UserCollectShopMapper mapper;

    @Autowired
    public UserCollectShopServiceImpl(UserCollectShopMapper mapper) {
        super(mapper);
        this.mapper = mapper;
    }

    @Override
    public UserCollectShop collect(User user, Shop shop) {
        UserCollectShop log = findByUserAndShop(user, shop);
        if (log == null) {
            log = new UserCollectShop();
            log.setShopId(shop.getId());
            log.setUserId(user.getId());
            log = save(log);
        }
        log.setShop(shop);
        log.setUser(user);
        return log;
    }

    @Override
    public UserCollectShop findByUserAndShop(User user, Shop shop) {
        UserCollectShop query = new UserCollectShop();
        query.setUserId(user.getId());
        query.setShopId(shop.getId());
        return findOneByQuery(query);
    }

    @Override
    public PageInfo<UserCollectShop> findByUserId(Integer userId, Integer page, Integer rows) {
        return PageHelper.startPage(page, rows)
                .doSelectPageInfo(() -> mapper.selectByUserInfoFetchAll(userId));
    }

    @Override
    public boolean isCollected(Integer userId, Integer shopId) {
        UserCollectShop query = new UserCollectShop();
        query.setUserId(userId);
        query.setShopId(shopId);
        return exists(query);
    }

    @Override
    public UserCollectShop unCollect(User user, Shop shop) {
        UserCollectShop query = new UserCollectShop();
        query.setUserId(user.getId());
        query.setShopId(shop.getId());
        UserCollectShop ucs = findOneByQuery(query);
        if (ucs == null) {
            throw new BadRequestException("未收藏该商铺");
        }
        if (deleteById(ucs.getId())) {
            return ucs;
        }
        throw new InternalServerErrorException("删除收藏记录失败");
    }
}
